package com.tongxin.van.frameworkcanary;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.tongxin.van.frameworkcanary.base.BaseActivity;

import org.greenrobot.eventbus.EventBus;

public class MainActivity extends BaseActivity {


    @Override
    protected int layoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void getBundleData(Bundle bundle) {

    }

    @Override
    protected void initTitlebar() {

    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void loadData() {
        checkNotifcationPermission();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    /**
     * 检测通知权限
     */
    private void checkNotifcationPermission() {
        NotificationManagerCompat manager = NotificationManagerCompat.from(getApplicationContext());
        boolean isOpened = manager.areNotificationsEnabled();
        if (!isOpened && !SPUtils.getInstance().contains("hasShowNotifcationDialog")) {
            new AlertDialog.Builder(this)
                    .setTitle("需要通知权限")
                    .setMessage("检测到您没有开启通知权限，请前往设置中开启")
                    .setPositiveButton("前往开启", (dialog, which) -> {
                        SPUtils.getInstance().put("hasShowNotifcationDialog", true);
                        Intent intent = new Intent();
                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", getPackageName(), null);
                        intent.setData(uri);
                        startActivity(intent);
                    })
                    .setNegativeButton("以后再说", (dialog, which) -> SPUtils.getInstance().put("hasShowNotifcationDialog", true))
                    .create().show();

        }
    }

    /**
     * 返回键处理
     * 双击退出
     */
    private long exittime;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - exittime < 1500) {
            super.onBackPressed();
        } else {
            exittime = System.currentTimeMillis();
            ToastUtils.showShort("再按一次退出程序");
        }
    }
}
